from flask import Blueprint, render_template, request, jsonify, redirect
from flask_login import login_user, logout_user, current_user, AnonymousUserMixin, login_required
from Config import db
from models.my_model import Post, Like, Comment, User, R, Reply
import datetime

comment_post = Blueprint("comment_post", __name__)


@comment_post.route("/comment/<int:post_id>", methods=['GET', "POST"])
@login_required
def all_post(post_id):
    cu: User = current_user
    if current_user.is_anonymous == True:
        # return jsonify(R(code=400, msg=f"no user logged in").define())
        return render_template("error_with_msg.html", msg="400 - 无登录用户")
    if request.method == "POST":
        """              
        帖子评论             
        :param post_id: 帖子ID  
        :user_id: 帖子用户id    
        :post_id: 帖子id  
        :textarea:评论内容  
        :current_datetime:当前时间  
        """
        user_id = current_user.id
        post = Post.query.filter(Post.id == post_id).first()
        textarea = request.form.get('textarea')
        # 获取当前日期和时间
        current_datetime = datetime.datetime.now()
        # 输出当前日期和时间
        print("Current Date and Time:", current_datetime)
        print(user_id, post.user_id, post_id, textarea, current_datetime)
        comment: Comment = Comment(
            user_id=user_id,
            target_user_id=post.user_id,
            target_post_id=post_id,
            content=textarea,

        )
        # 添加数据库
        db.session.add(comment)

        # 更新文章评论数
        updata_commment(post_id)
        # 提交
        db.session.commit()
    return redirect('/post/' + str(post_id))


@comment_post.route("/comment/delete", methods=['GET', "POST"])
def remove_comment():
    '''
    删除评论
    :return: 
    '''
    data = request.get_json()
    print(data)
    # 根据id查询并删除
    post_id = Comment.query.filter(Comment.id == data['comment_id']).first().target_post_id
    Comment.query.filter(Comment.id == data['comment_id']).delete()
    Reply.query.filter(Reply.comment_post_id == data['comment_id']).delete()

    # 更新文章评论数
    updata_commment(post_id)

    db.session.commit()

    # return redirect('http://127.0.0.1:5000/post/'+str(data['target_user_id']))
    return jsonify({"data": "1"})


@comment_post.route("/comment/reply", methods=['GET', "POST"])
def comment_reply():
    """
    评论回复
    :return:
    """
    print("Adsdaasdasdasdasdasdasd")

    data = request.get_json()
    print(data)
    reply: Reply = Reply(
        user_id=data['user_id'],
        comment_post_id=data['comment_post_id'],
        target_post_id=data['target_post_id'],
        content=data['reply_text']
    )
    # 添加数据库
    db.session.add(reply)
    # 提交
    db.session.commit()
    return jsonify({"data": "1"})


@comment_post.errorhandler(401)
def user_err_401(error):
    return render_template("error_with_msg.html", msg="拒绝访问", detail="您可能尚未登录或是权限不足")


def updata_commment(id):
    comments: list = Comment.query.filter(Comment.target_post_id == id).all()
    comment_count = len(comments)  # 获取评论总数
    session: db.session = db.session()
    post = Post.query.filter(Post.id == id).first()
    post.comment_count = comment_count
    session.merge(post)
